package com.gy.service.impl;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gy.controller.common.UploadController;
import com.gy.controller.common.UserHolder;
import com.gy.entity.research.Horizontal;
import com.gy.entity.research.Longitudinal;
import com.gy.mapper.HorizontalMapper;
import com.gy.query.HorizontalQuery;
import com.gy.result.Result;
import com.gy.service.HorizontalService;
import com.gy.service.UserService;
import com.gy.vo.PageVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class HorizontalServiceImpl extends ServiceImpl<HorizontalMapper, Horizontal> implements HorizontalService {

    @Autowired
    private UploadController uploadController;
    @Autowired
    private HorizontalMapper horizontalMapper;

    @Autowired
    private UserService userService;
    @Override
    public Result<PageVO<Horizontal>> getHorizontal(HorizontalQuery horizontalQuery) {
        Long userId = UserHolder.getUser().getUserId();
        if (userId == null) {
            return Result.error("用户登录信息异常");
        }

        // 分页条件
        Page<Horizontal> page = new Page<>(horizontalQuery.getPageNo(), horizontalQuery.getPageSize());

        // 排序条件
        if (!horizontalQuery.getSortBy().isEmpty() || horizontalQuery.getIsAsc() != null) {
            page.addOrder(new OrderItem(horizontalQuery.getSortBy(), horizontalQuery.getIsAsc()));
        } else {
            // 为空，默认按照获得时间排序
            page.addOrder(new OrderItem("obtain_time", false));
        }

        // 构建查询条件
        LambdaQueryChainWrapper<Horizontal> horizontalLambdaQueryChainWrapper = lambdaQuery()
                .eq(userId != null, Horizontal::getUserId, userId); // 根据用户ID查询

        // 只在开始日期和结束日期不为空且有效时添加 between 条件
        if (horizontalQuery.getStartTime()!= null && horizontalQuery.getEndTime() != null) {
            try {
                // 可以根据需求调整日期格式
                Date startDate = new SimpleDateFormat("yyyy-MM-dd").parse(horizontalQuery.getStartTime());
                Date endDate = new SimpleDateFormat("yyyy-MM-dd").parse(horizontalQuery.getEndTime());
                horizontalLambdaQueryChainWrapper.between(Horizontal::getStartTime, startDate, endDate);
            } catch (ParseException e) {
                // 处理日期解析错误
                System.err.println("Invalid date format: " + e.getMessage());
            }
        }

        //添加个人排名查询参数
        if (horizontalQuery.getRank() != null) {
            horizontalLambdaQueryChainWrapper.eq(Horizontal::getRank, horizontalQuery.getRank());
        }
        // 分页查询
        Page<Horizontal> horizontalPage = horizontalLambdaQueryChainWrapper.page(page);

        // 封装结果
        PageVO<Horizontal> vo = new PageVO<>();
        vo.setTotal(horizontalPage.getTotal());
        vo.setPages(horizontalPage.getPages());
        List<Horizontal> records = horizontalPage.getRecords();

        if (records == null || records.isEmpty()) {
            vo.setList(Collections.emptyList());
        } else {
            vo.setList(records);
        }

        return Result.success(vo);
    }

    @Override
    @Transactional
    public Result removeHorizontalById(Long id) {
        Horizontal horizontal = getById(id);
        if (horizontal == null) {
            return Result.error("横向研究信息未找到");
        }

        String filePath = horizontal.getPdfPath();

        // 检查 filePath 是否为空
        if (filePath != null && !filePath.isEmpty()) {
            try {
                uploadController.deleteFile(filePath);
            } catch (Exception e) {
                return Result.error("删除文件失败");
            }
        } else {
            log.warn("filePath 为空，无需删除文件");
        }

        boolean removed = removeById(id);
        userService.decrementUserHorizontalCount();
        if (!removed) {
            return Result.error("删除横向研究信息失败");
        }

        return Result.success("横向研究信息删除成功");
    }

    @Override
    public Result updateHorizontal(Horizontal horizontal) {
        // 参数验证
        if (horizontal == null) {
            return Result.error("横向研究信息不能为空");
        }
        if (horizontal.getId() == null) {
            return Result.error("横向课题ID不能为空");
        }

        try {
            // Attempt to update the horizontal research data
            int affectedRows = horizontalMapper.updateHorizontal(horizontal);
            if (affectedRows > 0) {
                return Result.success(horizontal);
            } else {
                return Result.error("未找到对应的横向研究信息进行更新");
            }
        } catch (Exception e) {
            // 记录日志
            log.error("更新横向研究信息时发生异常", e);
            return Result.error("更新横向研究信息失败");
        }
    }

    @Override
    @Transactional
    public Result saveHorizontal(Horizontal horizontal) {
        // Step 1: Validate input
        if (horizontal == null) {
            log.warn("传入的横向课题对象为空");
            return Result.error("横向课题对象不能为空");
        }

        try {
            // Step 2: Set user ID, ensuring the user is authenticated
            Long userId = UserHolder.getUser().getUserId();
            if (userId == null) {
                return Result.error("用户登录信息异常");
            }
            horizontal.setUserId(userId);

            // Step 3: Save the horizontal research data
            boolean saved = horizontalMapper.saveHorizontal(horizontal);  // Using MyBatis Plus's save() method
            if (!saved) {
                return Result.error("新增横向课题失败");
            }

            userService.incrementUserHorizontalCount();
            // Step 5: Return success response
            return Result.success("新增横向课题成功");
        } catch (Exception e) {
            // Step 6: Handle any exceptions and log them
            log.error("保存横向课题时发生异常", e);
            return Result.error("系统错误，请稍后再试");
        }
    }

    @Override
    public Result getHorizontalByIds(Long[] ids) {
        // 验证传入的ID数组
        if (ids != null && ids.length > 0) {
            try {
                // 使用原生 MyBatis 查询横向课题
                List<Horizontal> horizontalList = horizontalMapper.selectHorizontalBatchIds(Arrays.asList(ids));

                // 返回查询结果
                if (horizontalList != null && !horizontalList.isEmpty()) {
                    return Result.success(horizontalList);
                } else {
                    return Result.error("未找到相关横向课题信息");
                }
            } catch (Exception e) {
                log.error("根据多个id查询横向课题时发生异常", e);
                return Result.error("查询横向课题失败");
            }
        }
        return Result.error("未提供有效的横向课题ID");
    }

    @Override
    public Horizontal getHorizontalById(Long id) {
        if (id == null) {
            return null;
        }
        return horizontalMapper.selectHorizontalById(id);
    }



}
